package hive.function;

import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentTypeException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class GetCityByPhoneNum extends GenericUDF {

    //初始化手机号段
    String[] phoneNumHeaders = {"138","159","188"};
    //初始化原始区号与城市的对应Map
    static Map<String,String> cityMap = new HashMap<String,String>();

    String areaNum = "";
    String message = "";

    static{
        cityMap.put("0451", "哈尔滨");
        cityMap.put("0452", "齐齐哈尔");
        cityMap.put("0453", "牡丹江");
        cityMap.put("0454", "佳木斯");
    }


    @Override
    public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException {
        // 判断输入参数的个数
        if(arguments.length !=1){
            throw new UDFArgumentLengthException("Input Args Length Error!!!");
        }
        // 判断输入参数的类型
        if(!arguments[0].getCategory().equals(ObjectInspector.Category.PRIMITIVE)){
            throw new UDFArgumentTypeException(0,"Input Args Type Error!!!");
        }
        //函数本身返回值为String，需要返回String类型的鉴别器对象
        return PrimitiveObjectInspectorFactory.javaStringObjectInspector;
    }

    @Override
    public Object evaluate(DeferredObject[] arguments) throws HiveException{

        System.out.println(Arrays.toString(arguments));

        String phoneNum = arguments[0].get().toString();

        int phoneSize = phoneNum.length();

        //电话号为11位或12位且以0开头的，就是固话
        if((phoneSize==11 || phoneSize==12) && phoneNum.startsWith("0")){
            //取固话的前4位数作为区号
            areaNum = phoneNum.substring(0,4);
        }else if(phoneSize==11 && phoneNum.startsWith("1")){
            //电话号是11位且以1开头，就是手机号
            //取手机的号段
            String phoneNumHeader = phoneNum.substring(0,3);
            //把号段的数组转成List，判断当前号段是否合法
            if(Arrays.asList(phoneNumHeaders).contains(phoneNumHeader)){
                areaNum = phoneNum.substring(3,7);
            }else{
                message = "号段错误";
            }
        }else{
            message = "格式错误";
        }

        //格式正确，区号也存在，返回相应城市
        if(cityMap.containsKey(areaNum)){
            message = cityMap.get(areaNum);
        }else if(null!=areaNum && !areaNum.equals("")){
            //格式正确，区号不存在，返回提示
            message = "未知归属地";
        }

        return message;
    }

    @Override
    public String getDisplayString(String[] strings) {
        return "";
    }
}
